from urllib.request import build_opener, HTTPCookieProcessor, Request
from http.cookiejar import CookieJar
import io
import random
import json


import time


def encode_data(data):
    try:
        return bytes(data, 'utf-8')
    except:
        return bytes(data)


def decode_data(data):
    return io.StringIO(data.read().decode('utf-8'))


base_url = 'http://localhost:8069'
base_url = 'http://43.143.148.83:8069'


taxno = ''
appkey = 'vwat.apon'
# appsecret = '4373284184f3f12937766a1bb5901a58af8108e4'  # 'http://localhost:8069'

# 'http://43.143.148.83/:8069'
appsecret = '4373284184f3f12937766a1bb5901a58af8108e4'


def json_call(url, params):
    data = {
        "jsonrpc": "2.0",
        "method": "call",
        "id": random.randint(0, 1000000000),
        "params": params,
    }

    data_json = json.dumps(data)

    # print('url=', url)
    # print('data=', data)
    request = Request(url=url, data=encode_data(data_json))
    request.add_header('Content-Type', 'application/json')
    cookie_jar = CookieJar()
    opener = build_opener(HTTPCookieProcessor(cookie_jar))
    response = opener.open(request, timeout=50000)
    # print('response:', response.data.read())

    # print('response1', response.headers)

    data = json.load(decode_data(response))
    # print('response:', data)

    error = data.get('error')
    if error:

        print('error,', error)

        raise

    result = data.get('result', {})
    # print('result:', result)
    return result


def access_token(base_url, appkey, appsecret):
    url = '/vwat/access/token'
    full_url = base_url + url

    params = {
        'taxno': taxno,
        'appkey': appkey,
        'appsecret': appsecret,
    }

    result = json_call(full_url, params)
    token = result.get('token')
    # print('access_token=', result)
    return token


def test_version():
    url = '/web/webclient/version_info'
    full_url = base_url + url
    params = {}
    result = json_call(full_url, params)
    print('test_version:', result)


def test_token():
    appkey = 'vwat.apon'
    # appsecret = 'f703930437e7f33fa1fabe68045d7be5ba47cb4f'

    token = access_token(base_url, appkey, appsecret)
    print('test_token', token)


def test_one_url(token):
    if not token:
        return

    url = '/vwat/test'
    full_url = base_url + url

    params = {
        'token': token,
        'test1': 12345678,
        'test2': 'qweweqwwe',
    }

    result = json_call(full_url, params)

    print('test_one_url result:', result)


def test_api(token):

    if not token:
        return

    url = '/vwat/test_api'
    full_url = base_url + url

    params = {
        'token': token,
        'p1': 12345678,
        'p2': 'qweweqwwe',
    }

    result = json_call(full_url, params)

    print('test_api result:', result)


def test_upload(token):
    if not token:
        return

    url = '/vwat/invoice/upload'
    full_url = base_url + url

    params = {
        'token': token,
        'filedata': '',
        'emp_name': '',
        'emp_number': '',
        'invoice_tag': '',
        'vendor_name': '',
        'bank_name': '',
        'account_no': '',
    }

    result = json_call(full_url, params)

    print('test_upload result:', result)


def test_list(token):
    if not token:
        return

    url = '/vwat/invoice/list'
    full_url = base_url + url

    params = {
        'token': token,
        'emp_name': '',
        'emp_number': '',
        'invoice_tag': '',
        'filter': {
            'apon_status': '',
            'code': '',
            'number': '',
        }

    }

    result = json_call(full_url, params)

    print('test_list result:', result)


def test_delete(token):
    if not token:
        return

    url = '/vwat/invoice/delete'
    full_url = base_url + url

    params = {
        'token': token,
        'code': '',
        'number': '',
        'emp_name': '',
        'emp_number': '',
        'apon_number': '123123',

    }

    result = json_call(full_url, params)

    print('test_delete result:', result)


def test_update(token):
    if not token:
        return

    url = '/vwat/invoice/update'
    full_url = base_url + url

    params = {
        'token': token,
        'code': '',
        'number': '',
        'emp_name': '',
        'emp_number': '',
        'apon_number': '123123',
        # submitted, approved，Finished，Declined，Rejected. Cancelled，Draft，Invalid, withdraw
        'apon_status': 'submitted'

    }

    result = json_call(full_url, params)

    print('test_update result:', result)


test_version()
# url= http://43.143.148.83:8069/web/webclient/version_info
# data= {'jsonrpc': '2.0', 'method': 'call', 'id': 557176240, 'params': {}}
# response: {'jsonrpc': '2.0', 'id': 557176240, 'result': {'server_version': '16.0-20230102', 'server_version_info': [16, 0, 0, 'final', 0, ''], 'server_serie': '16.0', 'protocol_version': 1}}

test_token()
# url= http://43.143.148.83:8069/vwat/access/token
# data= {'jsonrpc': '2.0', 'method': 'call', 'id': 469774594, 'params': {'taxno': '', 'appkey': 'vwat.apon', 'appsecret': 'a472a97bfc12a35adb26176eda03ffd8fe6cd3f8'}}
# response: {'jsonrpc': '2.0', 'id': 469774594, 'result': {'token': '30bbad3f346182ec36df7b63cdcbc03319247fb2'}}


# time.sleep(6)

token = access_token(base_url, appkey, appsecret)
print('token', token)
test_api(token)
# url= http://43.143.148.83:8069/vwat/test_api
# data= {'jsonrpc': '2.0', 'method': 'call', 'id': 208678494, 'params': {'token': 'a1000897e263fc6183a62489b00fa9fc0cd5e538', 'p1': 12345678, 'p2': 'qweweqwwe'}}
# response: {'jsonrpc': '2.0', 'id': 208678494, 'result': 'you call success by (12345678,qweweqwwe)'}

# test_one_url(token)
# url= http://43.143.148.83:8069/vwat/test
# data= {'jsonrpc': '2.0', 'method': 'call', 'id': 423796170, 'params': {'token': 'bc90c4ad7527570a83450d4c3c97ba50988331fe', 'test1': 12345678, 'test2': 'qweweqwwe'}}
# response: {'jsonrpc': '2.0', 'id': 423796170, 'result': [{'id': 3, 'name': 'Administrator'}, {'id': 7, 'name': 'Apon'}, {'id': 1, 'name': 'My Company'}]}

test_upload(token)
test_list(token)
test_delete(token)
test_update(token)


# 对公业务, 一条发票的数据:

fp = {
    'code': '011002100111',  # 发票代码
    'number': '15151122',  # 发票号码
    'amount_total': 1130.0,  # 含税总金额
    'amount_untax': 1000.0,  # 不含税总金额
    'amount_tax': 130.0,  # 税额
    'data': '2022-08-28',  # 开票日期
    'remark': '备注',  # 备注
    'todo_name_here': 'todo_demo_data',  # 信息核对是否一致
    'todo_name_here': 'todo_demo_data',  # 收票日期
    'todo_name_here': 'todo_demo_data',  # 使用情况
    'todo_name_here': 'todo_demo_data',  # 申请单号
    'todo_name_here': 'todo_demo_data',  # URL-发票源文件存储地址 URL地址
    'todo_name_here': 'todo_demo_data',  # 图片
    'lines': [
        {
            'product_name': '苹果笔记本',  # 商品名称
            'product_spec': '4CPU,8G,256G',  # 规格
            'product_uom': '台',  # 单位
            'quantity': 10,  # 数量
            'price': 1000,  # 不含税单价
            'amount_untax': 10000.0,  # 不含税金额
            'amount_tax': 1300.0,  # 税额
        }
    ]

}


# 对私业务, 一条发票的数据:

fp = {
    'invoice_type': 'vat_genaral_e',  # 发票类型
    'code': '011002100111',  # 发票代码
    'number': '15151122',  # 发票号码
    'amount_total': 1130.0,  # 含税总金额
    'amount_untax': 1000.0,  # 不含税总金额
    'amount_tax': 130.0,  # 税额
    'data': '2022-08-28',  # 开票日期
    'remark': '备注',  # 备注


    'todo_name_here': 'todo_demo_data',  # 使用情况
    'todo_name_here': 'todo_demo_data',  # 申请单号
    'todo_name_here': 'todo_demo_data',  # URL-发票源文件存储地址 URL地址
    'todo_name_here': 'todo_demo_data',  # 图片
    'lines': [
        {
            'product_name': '苹果笔记本',  # 商品名称
            'product_spec': '4CPU,8G,256G',  # 规格
            'product_uom': '台',  # 单位
            'quantity': 10,  # 数量
            'price': 1000,  # 不含税单价
            'amount_untax': 10000.0,  # 不含税金额
            'amount_tax': 1300.0,  # 税额
        }
    ]

}
